/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package COBRANZA_CONTROLLER;

import COBRANZA_MODELO.COB_FACTURA;
import COBRANZA_MODELO.COB_FACTURA_DETALLE;
import CONTABILIDAD_MODELO.CON_CODIGO_CONTROL;
import CONTABILIDAD_MODELO.CON_DATOS_EMPRESA;
import CONTABILIDAD_MODELO.CON_PARAMETROS_FACTURAS;
import CONTABILIDAD_MODELO.CON_SUCURSAL_PARAMETROS;
import Conexion.Conexion;
import RRHH_Modelo.RHH_USUARIO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author equipo_4
 */
@WebServlet(name = "COB_FACTURA_CONTROLLLER", urlPatterns = {"/COB_FACTURA_CONTROLLLER"})
public class COB_FACTURA_CONTROLLLER extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
           
           
        } finally {            
            out.close();
        }
    }

    public void anularFactura(Conexion con, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException
    {
        double id = Double.parseDouble(request.getParameter("id"));
        COB_FACTURA factura = new COB_FACTURA();
        factura.setCon(con);
        factura.anular(id);
        response.sendRedirect("COBRANZAS/COB_LISTAR_FACTURAS.jsp");
    }
    
    public void InsertarFactura(Conexion con, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ParseException, Exception
    {                
            con.Transacction();
            
           String comprador = request.getParameter("razonSoc_cli");
           String NIT_CI = request.getParameter("nit_cli");
           String tipo_movimiento = request.getParameter("tipo_fact");
           Double sucur = Double.parseDouble(request.getParameter("suc"));
           Double totalf = Double.parseDouble(request.getParameter("total"));
           String total_lit = request.getParameter("total_lit");
           int length = Integer.parseInt(request.getParameter("length"));
           
           COB_FACTURA factura = new COB_FACTURA();
           factura.setNIT(NIT_CI);
           factura.setMONTO_NUMERAL(totalf);
           factura.setMONTO_LITERAL(total_lit);
           factura.setESTADO_ANULADO(0);
           Date dt = Calendar.getInstance().getTime();           
           factura.setFECHA_FACTURA(dt);
           factura.setID_SUCURSAL(sucur);           
           factura.setCARACTERISTICA("");
           
           
             
            CON_DATOS_EMPRESA empresa = new CON_DATOS_EMPRESA(con);
            empresa = empresa.Todos().get(0);

            CON_SUCURSAL_PARAMETROS csp = new CON_SUCURSAL_PARAMETROS();
            csp.setCon(con);
            csp=csp.BuscarXSucursal(sucur);

            CON_PARAMETROS_FACTURAS cpf = new CON_PARAMETROS_FACTURAS();
            cpf.setCon(con);
            cpf = cpf.BuscarXid(csp.getID_PARAMETROS_FACTURA());
           
            String nauto = cpf.getNRO_AUTORIZACION();
            
            int nfact = (int)factura.getNroFactura();
            String nit = empresa.getNIT();
            String llave = cpf.getLLAVE_CIFRADO();
            
            DateFormat format = new SimpleDateFormat("ddMMYYYY");       
            String limite1 = cpf.getTIEMPO_VIGENCIA();
            DateFormat format2 = new SimpleDateFormat("dd/MM/YYYY");              
            Date limite = format2.parse(limite1);
            
            long diferencia =  limite.getTime()-dt.getTime();
            double dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));
            
            if(dias>0)
            {
                String valor = CON_CODIGO_CONTROL.GetCodigo(nauto, nfact+"", nit, format.format(dt), totalf+"", llave);
            
                factura.setCODIGO_CONTROL("");
                factura.setNRO_AUTORIZACION("");
                factura.setNUMERO_FACTURA(0.0);
                factura.setTIPO_FACTURA("");
                factura.setTIPO_MOVIMIENTO(0.0);

                factura.setCon(con);
           
                factura.Insertar();
                factura = factura.Buscar();
                
           
                for (int i = 0; i < length; i++) 
                {
                    COB_FACTURA_DETALLE fd = new COB_FACTURA_DETALLE();
                    fd.setCon(con);
                    Double cant = Double.parseDouble(request.getParameter("json["+i+"][cant]"));
                    String conc = request.getParameter("json["+i+"][desc]");
                    Double pu = Double.parseDouble(request.getParameter("json["+i+"][pu]"));
                    Double tot = Double.parseDouble(request.getParameter("json["+i+"][total]"));
                    fd.setCANTIDAD(cant);
                    fd.setDETALLE(conc);
                    fd.setP_UNITARIO(pu);
                    fd.setSUB_TOTAL(tot);
                    fd.setID_FACTURA(factura.getID());
                    fd.Insertar();
                }
            }
            else
            {
            con.rollback();
            }         
            con.commit();
           response.sendRedirect("COBRANZAS/MostrarFactura.jsp?id="+factura.getID());
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(COB_FACTURA_CONTROLLLER.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            RHH_USUARIO usuario = ((RHH_USUARIO)request.getSession().getAttribute("usr"));
             Conexion con = new Conexion(usuario.getPASSWORD(), usuario.getPASSWORD());
            
             String evento = request.getParameter("evento");
             
             switch(evento)
             {
                 case "insertar":
                     InsertarFactura(con, request, response);
                     break;
                 case "anular":
                     anularFactura(con, request, response);
                     break;
             }
        } catch (SQLException ex) {
            Logger.getLogger(COB_FACTURA_CONTROLLLER.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(COB_FACTURA_CONTROLLLER.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(COB_FACTURA_CONTROLLLER.class.getName()).log(Level.SEVERE, null, ex);
        }
            
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
